package org.example.studentmanager.controller;

import org.example.studentmanager.model.Root;
import org.example.studentmanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    @GetMapping("/register")
    public String showRegisterPage(Model model) {
        model.addAttribute("root", new Root());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(Root root, Model model) {
        try {
            userService.loadUserByUsername(root.getUsername());
            model.addAttribute("error", "用户名已存在");
            return "register";
        } catch (UsernameNotFoundException e) {
            // 对密码进行编码
            String encodedPassword = passwordEncoder.encode(root.getPassword());
            root.setPassword(encodedPassword);
            root.setRole("ROLE_USER");
            userService.saveRoot(root);
            return "redirect:/login";
        }
    }
}